package cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.util;

import cn.hutool.core.io.FileUtil;
import cn.maihe.elg.operation.utils.ElgLogger;
import com.kinsec.KTConvert;
import com.kinsec.dom.Attachment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Map;

/**
 * @Description
 * @Author WJH
 * @Date 2022/10/12
 */
@Slf4j
public class KtOfdCloudConvertUtil {

    private KTConvert ofdKTConvert;

    public KtOfdCloudConvertUtil(KTConvert ofdKTConvert) {
        this.ofdKTConvert = ofdKTConvert;
        Assert.notNull(ofdKTConvert, () -> "ofdKTConvert不能为空");
    }

    /**
     * 验证待转换文件的扩展名 必须为：pdf|doc|docx|xls|xlsx|html
     */
    private boolean enableExtName(Path sourceOfficePath) {
        String extName = FileUtil.extName(sourceOfficePath.toFile()).toLowerCase();
        boolean tf = extName.matches("ofd|pdf|doc|docx|xls|xlsx|html");
        if (!tf) {
            throw new RuntimeException("不支持文件转换类型[" + extName + "]");
        }
        return true;
    }

    /**
     * 将单个excel文件(支持html,pdf,doc,docx,xls,不支持jpg,png)转换为OFD文件
     */
    public Path office2Ofd(Path sourceOfficePath, Path targetOfdPath) {
        this.enableExtName(sourceOfficePath);
        Assert.isTrue(targetOfdPath.toString().toLowerCase().endsWith(".ofd"), "转换后文件必须为ofd类型");
        try {
            ofdKTConvert.kt_officeToOFD(sourceOfficePath.normalize().toString(), Files.newOutputStream(targetOfdPath));
            if (Files.notExists(targetOfdPath) || Files.size(targetOfdPath) == 0) {
                throw new RuntimeException("转换后ofd文件不存在或大小为0");
            }
        } catch (Exception e) {
            throw new RuntimeException("云签pdf转ofd异常:" + e.getMessage(), e);
        }
        return targetOfdPath;
    }

    /**
     * 将单个excel文件(支持html,pdf,doc,docx,xls,不支持jpg,png)转换为OFD文件
     */
    public Path office2OfdWithMetas(Path sourceOfficePath, Path targetOfdPath, Map<String, String> metas) {
        this.enableExtName(sourceOfficePath);
        Assert.isTrue(targetOfdPath.toString().toLowerCase().endsWith(".ofd"), "转换后文件必须为ofd类型");
        try {
            ElgLogger.info(log, l -> l.info("guaranteeNo={} << kt_office2OfdWithMetas请求:源文件->{},目标文件->{},metas->{}", metas.get("电子投标保函编号"), sourceOfficePath.getFileName(), targetOfdPath.getFileName(), metas));
            ofdKTConvert.kt_officeToOFD(sourceOfficePath.normalize().toString(), Files.newOutputStream(targetOfdPath), metas);
            if (Files.notExists(targetOfdPath) || Files.size(targetOfdPath) == 0) {
                throw new RuntimeException("转换后ofd文件不存在或大小为0");
            }
        } catch (Exception e) {
            throw new RuntimeException("云签pdf转ofd异常:" + e.getMessage(), e);
        }
        return targetOfdPath;
    }

    /**
     * 将单个excel文件(支持html,pdf,doc,docx,xls,不支持jpg,png)转换为OFD文件 自定义docId
     */
    public Path office2Ofd(Path sourceOfficePath, String docId, Path targetOfdPath) {
        this.enableExtName(sourceOfficePath);
        Assert.isTrue(targetOfdPath.toString().toLowerCase().endsWith(".ofd"), "转换后文件必须为ofd类型");
        try {
            ofdKTConvert.kt_officeToOFD(sourceOfficePath.normalize().toString(), docId, Files.newOutputStream(targetOfdPath));
            if (Files.notExists(targetOfdPath) || Files.size(targetOfdPath) == 0) {
                throw new RuntimeException("转换后ofd文件不存在或大小为0");
            }
        } catch (Exception e) {
            throw new RuntimeException("云签pdf转ofd异常:" + e.getMessage(), e);
        }
        return targetOfdPath;
    }

    /**
     * 将单个excel文件(支持html,pdf,doc,docx,xls,不支持jpg,png)转换为OFD文件  自定义docId
     */
    public Path office2OfdWithMetas(Path sourceOfficePath, String docId , Path targetOfdPath, Map<String, String> metas) {
        this.enableExtName(sourceOfficePath);
        Assert.isTrue(targetOfdPath.toString().toLowerCase().endsWith(".ofd"), "转换后文件必须为ofd类型");
        try {
            ElgLogger.info(log, l -> l.info("guaranteeNo={} << kt_office2OfdWithMetas请求:源文件->{},目标文件->{},metas->{}", metas.get("电子投标保函编号"), sourceOfficePath.getFileName(), targetOfdPath.getFileName(), metas));
            ofdKTConvert.kt_officeToOFD(sourceOfficePath.normalize().toString(), docId, Files.newOutputStream(targetOfdPath), metas);
            if (Files.notExists(targetOfdPath) || Files.size(targetOfdPath) == 0) {
                throw new RuntimeException("转换后ofd文件不存在或大小为0");
            }
        } catch (Exception e) {
            throw new RuntimeException("云签pdf转ofd异常:" + e.getMessage(), e);
        }
        return targetOfdPath;
    }


    public static class MyAttachment {
        ArrayList<Attachment> attachments = new ArrayList<>();

        public static MyAttachment init() {
            return new MyAttachment();
        }

        public MyAttachment add(String title, String fileType, Path attachmentPath) {
            try {
                attachments.add(new Attachment(title, fileType, Files.newInputStream(attachmentPath)));
            } catch (IOException e) {
                throw new RuntimeException("添加附件[" + attachmentPath.normalize().toString() + "]异常");
            }
            return this;
        }

        public ArrayList<Attachment> getAttachments() {
            return attachments;
        }
    }

    /**
     * 将单个excel(支持ofd,pdf)文件转换为OFD文件并添加附件
     *
     * @param attachmentList 通过new MyAttachment().add(title,fileType,attaPath).add...().getAttachments()
     * @return
     */
    public Path addAttachments(Path sourceOfficePath, Path targetOfdPath, ArrayList<Attachment> attachmentList) {
        Assert.isTrue(targetOfdPath.normalize().toString().toLowerCase().endsWith(".ofd"), "转换后文件必须为ofd类型");
        String extName = FileUtil.extName(sourceOfficePath.toFile()).toLowerCase();
        boolean tf = extName.matches("ofd|pdf");
        if (!tf) {
            throw new RuntimeException("不支持文件转换类型[" + extName + "]");
        }
        try {
            ofdKTConvert.kt_addAttachment(sourceOfficePath.toFile(), Files.newOutputStream(targetOfdPath), attachmentList);
            if (Files.notExists(targetOfdPath) || Files.size(targetOfdPath) == 0) {
                throw new RuntimeException("ofd添加附件后文件不存在或大小为0");
            }
        } catch (Exception e) {
            throw new RuntimeException("ofd添加附件异常:" + e.getMessage(), e);
        }
        return targetOfdPath;
    }


    public static void main(String[] args) {
        KTConvert ktConvert = new KTConvert("58.22.60.120:18880");
//        KTConvert ktConvert = new KTConvert("47.107.97.45:8880");
        KtOfdCloudConvertUtil util = new KtOfdCloudConvertUtil(ktConvert);
//        KTSignature sign = new KTSignature("47.107.97.45:8880");
//        KtOfdCloudSignatureUtil ofdSign  = new KtOfdCloudSignatureUtil(sign);

//        Path doc = Paths.get("d:/11111111111/担保保函.doc");
//        Path docx = doc.resolveSibling("担保保函.docx");
//
//
//        util.office2Ofd(pdf2, ofd1);
//        util.office2Ofd(doc1, ofd2);

        //添加附件
//        Path doc2ofdWithAttach = doc2ofd.resolveSibling("03担保保函文件模板doc2pdfAnd添加附件.ofd");
//        Path pdf2ofdWithAttach = pdf2ofd.resolveSibling("03担保保函文件模板pdf2ofdAnd添加附件.ofd");
//        ArrayList<Attachment> attachments = new MyAttachment()
//                .add("pdf附件标题", "pdf", pdf).getAttachments();
//        util.addAttachments(doc2ofd, doc2ofdWithAttach, attachments);
//
//        ArrayList<Attachment> attachments2 = new MyAttachment()
//                .add("doc附件标题", "docx", doc).getAttachments();
//        util.addAttachments(pdf, pdf2ofdWithAttach, attachments2);


    }


}
